from django.shortcuts import render, render_to_response
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from django.core.urlresolvers import reverse
import json
from users.models import User
from publish.models import *
from publish.forms import *


# Create your views here.
@login_required()
def project_list(request):
    header_title, sub_title, path1, path2 = "", "", "发布管理", "项目配置"
    return render(request, 'publish/project_list.html', locals())


@login_required()
def project_getlist(request):
    project_env = PROJECT_ENV
    # print(project_env[1][1])
    dict_audit = {"0": "否", "1": "是"}

    offset = request.GET.get('offset', None)
    limit = request.GET.get('limit', None)
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', None)
    search = request.GET.get('search', None)

    if sort is None:
        sort = "name"
    if order == "desc":
        sort = "-name"
    count = Project.objects.all().count()
    pro_list = Project.objects.order_by(sort).all()[int(offset):int(offset + limit)]
    if search is not None:
        pro_list = Project.objects.order_by(sort).filter(name__icontains=search)[int(offset):int(offset + limit)]
    rows = [{
        'id': p.id,
        'name': p.name,
        'env': project_env[int(p.env) - 1][1],
        'repo_mode': p.repo_mode,
        'audit': dict_audit.get(str(p.audit)),
        'status': p.status
    } for p in pro_list]
    data = {'total': count, 'rows': rows}
    return JsonResponse(data)


@login_required()
def project_conf(request):
    header_title, sub_title, path1, path2 = "", "", "发布管理", "配置项目"
    project_form = ProjectModelForm()
    project_env = PROJECT_ENV
    if request.method == 'POST':
        form_data = ProjectModelForm(request.POST)
        if form_data.is_valid():
            # p = form_data.cleaned_data
            # print(type(p))
            # print(p)
            # form_data.save()

            uid = request.user.id
            name = request.POST.get('name', None)
            env = request.POST.get('env')
            status = request.POST.get('status')
            # version
            repo_url = request.POST.get('repo_url')
            repo_username = request.POST.get('repo_username', None)
            repo_password = request.POST.get('repo_password', None)
            repo_mode = request.POST.get('repo_mode')
            # repo_type
            deploy_from = request.POST.get('deploy_from', None)
            excludes = request.POST.get('excludes', None)
            release_user = request.POST.get('release_user')
            release_to = request.POST.get('release_to')
            release_library = request.POST.get('release_library')
            hosts = request.POST.get('hosts')
            pre_deploy = request.POST.get('pre_deploy')
            post_depoly = request.POST.get('post_deploy')
            pre_release = request.POST.get('pre_release')
            post_release = request.POST.get('post_release')
            post_release_delay = request.POST.get('post_release_delay')
            audit = request.POST.get('is_audit')
            salt = request.POST.get('is_salt')
            keep_version_num = request.POST.get('keep_version_num')
            p = Project(user_id=uid, name=name, env=env, status=status,
                        repo_url=repo_url, repo_username=repo_username,
                        repo_password=repo_password, repo_mode=repo_mode, deploy_from=deploy_from, excludes=excludes,
                        release_user=release_user, release_to=release_to, release_library=release_library, hosts=hosts,
                        pre_deploy=pre_deploy, post_deploy=post_depoly, pre_release=pre_release,
                        post_release=post_release, post_release_delay=post_release_delay, audit=audit,
                        saltstack=salt,
                        keep_version_num=keep_version_num)
            p.save()
        else:
            # errors
            print(form_data.errors)
        return HttpResponseRedirect(reverse(project_list))
    return render(request, 'publish/project_conf.html', locals())


@login_required()
def project_edit(request):
    header_title, sub_title, path1, path2 = "", "", "发布管理", "项目配置"
    project_id = request.GET.get('projectid', None)
    project = Project.objects.get(id=project_id)
    project_form = ProjectModelForm()
    project_env = PROJECT_ENV
    if request.method == 'POST':
        pass
    project_form = ProjectModelForm(instance=project)
    return render(request, 'publish/project_edit.html', locals())


@login_required()
def project_preview(request):
    project_id = request.GET.get('projectid', None)
    p = Project.objects.get(id=project_id)
    return render(request, 'publish/project_preview.html', locals())


@login_required()
def project_del(request):
    """
    删除项目
    :param request: 
    :return: 
    """
    ret = {'code': 0, 'message': ''}
    if request.method == 'POST':
        ids = request.POST.getlist('ids[]')
        for id in ids:
            Project.objects.get(id=id).delete()
            ret['code'] = 1
            ret['message'] = '执行成功'
    return HttpResponse(json.dumps(ret))


@login_required()
def task_list(request):
    header_title, sub_title, path1, path2 = "", "", "发布管理", "上线单列表"
    return render(request, 'publish/task_list.html', locals())


@login_required()
def task_getlist(request):
    offset = request.GET.get('offset', None)
    limit = request.GET.get('limit', None)
    sort = request.GET.get('sort', None)
    order = request.GET.get('order', None)
    search = request.GET.get('search', None)

    if sort is None:
        sort = "title"
    if order == "desc":
        sort = "-title"
    count = Project.objects.all().count()
    pro_list = Task.objects.order_by(sort).all()[int(offset):int(offset + limit)]
    if search is not None:
        pro_list = Task.objects.order_by(sort).filter(title__icontains=search)[int(offset):int(offset + limit)]
    rows = [{
        'id': t.id,
        'user': getUserName(t.user_id),
        'project': getProjectName(t.project_id),
        # 'project_id': Project.objects.get(id=int(t.project_id)).name,
        'title': t.title,
        'updated_at': t.updated_at.strftime("%Y-%m-%d %H:%I:%S"),
        'branch': t.branch,
        'commit_id': t.commit_id,
        'status': t.status,
    } for t in pro_list]
    data = {'total': count, 'rows': rows}
    return JsonResponse(data)

# 获取用户名
def getUserName(userid):
    try:
        user = User.objects.get(id=int(userid))
        if user:
            return user.name
    except:
        return u'非法用户'

# 获取项目名
def getProjectName(projectid):
    env = PROJECT_ENV
    try:
        project = Project.objects.get(id=int(projectid))
        if project:
            return project.name + ' - ' + env[int(project.env) - 1][1]
    except:
        return u''


@login_required()
def task_submit(request):
    header_title, sub_title, path1, path2 = "", "", "发布管理", "选择项目"
    project_env = PROJECT_ENV
    # project_list = Project.objects.all()
    # 获取对象指定列
    # project_list = Project.objects.values_list('id', 'name', 'env').all()
    project_list = Project.objects.values('id', 'name', 'env').all()
    return render(request, 'publish/task_submit.html', locals())


@login_required()
def task_deploy(request):
    header_title, sub_title, path1, path2 = "", "", "发布管理", "部署上线"
    return render(request, 'publish/task_deploy.html', locals())


@login_required()
def record_list(request):
    header_title, sub_title, path1, path2 = "", "", "发布管理", "项目配置"
    return render(request, 'publish/record_list.html', locals())


@login_required()
def check(request):
    header_title, sub_title, path1, path2 = "", "", "发布管理", "线上文件指纹"
    return render(request, 'publish/check.html', locals())
